import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/auth/Login.vue'
import Layout from "@/layouts/Layout.vue";
import MainLayout from '@/components/home/MainLayout.vue'
import { getToken, checkToken } from '@/utils/auth'
import {ElMessage} from "element-plus";
import Products from "@/components/home/Products.vue";
const routes = [
  {
    //登录路由
    path: '/login',
    name: 'Login',
    component: () => Login,
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    //用户登录
    path: '/user/login',
    name: 'UserLogin',
    component: () => import('@/views/user/UserLogin.vue'),
    meta: {
      title: '用户登录',
      requiresAuth: false
    }
  },
    //用户主页面
  {
    path: '/home',
    name: "MainLayout",
    component: MainLayout,
    meta:{
      requiresAuth: true,
      roles: ['user','admin']
    },
    children: [
      {
        path: '',
        name: 'HomePage',
        component: () => import('@/components/home/HomePage.vue'),
        meta: {
          title: '首页',
          requiresAuth: true,
          roles: ['user', 'admin']
        }
      },
      {
        path: 'products',
        name: 'Products',
        component: Products
      },
      {
        path: 'cart',
        name: 'Cart',
        component: () => import('@/components/home/Cart.vue')
      },
      {
        path: 'checkout',
        name: 'Checkout',
        component: () => import('@/components/home/Checkout.vue'),
        meta: {
          title: '订单结算',
          requiresAuth: true,
          roles: ['user']
        }
      },
      {
        path: 'orders',
        name: 'Orders',
        component: () => import('@/components/home/Orders.vue'),
        meta: {
          title: '我的订单',
          requiresAuth: true,
          roles: ['user']
        }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/profile/UserProfile.vue'),
        meta: {
          title: '个人中心',
          hidden: true,
          roles: ['user','admin']
        }
      }
    ]
  },

    //管理员页面
  {
    //默认路由
    path: '/',
    component: Layout,
    redirect: '/employee',//重定向到员工管理
    meta:{
      requiresAuth: true,
      roles: 'admin'
    },
    children:[
      {
        //员工管理
        path: 'employee',
        name: 'EmployeeList',
        component: () => import('@/views/employee/List.vue'),
        meta: {
          title: '员工管理',
          icon: 'user',
          roles: 'admin'
        }
      },
      {
        path: 'category',
        name: 'Category',
        component: () => import('@/views/category/List.vue'),
        meta: {
          title: '分类管理',
          icon: 'category',
          roles: 'admin'
        }
      },
      // 菜品管理
      {
        path: 'dish',
        name: 'Dish',
        component: () => import('@/views/dish/List.vue'),
        meta: {
          title: '菜品管理',
          icon: 'food',
          roles: 'admin'
        }
      },
      {
        path: 'dish/add',
        name: 'DishAdd',
        component: () => import('@/views/dish/AddAndEdit.vue'),
        meta: {
          title: '添加菜品',
          hidden: true,
          roles: 'admin'
        }
      },
      {
        path: 'dish/edit/:id',
        name: 'editDish',
        component: () => import('@/views/dish/AddAndEdit.vue'),
        meta: {
          title: '编辑菜品',
          hidden: true,
          roles: 'admin'
        }
      },

      // 套餐管理
      {
        path: 'setmeal',
        name: 'SetMeal',
        component: () => import('@/views/setmeal/List.vue'),
        meta: {
          title: '套餐管理',
          icon: 'set-meal',
          roles: 'admin'
        }
      },
      {
        path: 'setmeal/add',
        name: 'SetMealAdd',
        component: () => import('@/views/setmeal/AddAndEdit.vue'),
        meta: {
          title: '添加套餐',
          hidden: true,
          roles: 'admin'
        }
      },
      {
        path: 'setmeal/edit/:id',
        name: 'SetMealEdit',
        component: () => import('@/views/setmeal/AddAndEdit.vue'),
        meta: {
          title: '编辑套餐',
          hidden: true,
          roles: 'admin'
        }
      },
      // 订单明细
      {
        path: 'order',
        name: 'Order',
        component: () => import('@/views/order/OrderManagement.vue'),
        meta: {
          title: '订单管理',
          icon: 'order',
          roles: 'admin'
        }
      },
      // {
      //   path: 'order/detail/:id',
      //   name: 'OrderDetail',
      //   component: () => import('@/views/order/Detail.vue'),
      //   meta: {
      //     title: '订单详情',
      //     hidden: true
      //   }
      // },

      // 个人中心
      // {
      //   path: 'profile',
      //   name: 'Profile',
      //   component: () => import('@/views/Profile.vue'),
      //   meta: {
      //     title: '个人中心',
      //     hidden: true
      //   }
      // }
    ]
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: {
      title: '404',
      requiresAuth: false
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach(async (to) => {
  // 1. 获取Token（不验证）
  const token = getToken()
  // 2. 获取角色
  const userRole = localStorage.getItem('userRole') || 'user';//默认普通用户

  // 3. 处理需认证路由
  if (to.meta.requiresAuth) {
    // 无Token或验证失败时退出
    if (!token || !(await checkToken())) {
      //给出信息提示
      ElMessage.error('身份验证失败')
      console.log("userRole",userRole)
      // 根据用户角色返回不同的登录页面
      const loginPath = userRole === 'admin' ? '/login' : '/user/login'

      return {
        path: loginPath,
        query: { redirect: to.fullPath } // 记录来源地址
      }
    }

    // 4. 处理角色
    if(to.meta.roles && !to.meta.roles.includes(userRole)){
      ElMessage.error('你没有权限访问')
      return userRole === 'admin' ? { path: '/employee' } : { path: '/user' }
    }
  }
  // 5. 其他情况放行
  return true
})

export default router